package com.nowcoder.community.controller;

import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.contant.Entity;
import com.nowcoder.community.contant.Topic;
import com.nowcoder.community.entity.Event;
import com.nowcoder.community.event.EventProducer;
import com.nowcoder.community.service.DisccusPostService;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.utils.CommunityUtils;
import com.nowcoder.community.utils.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;

@Controller
@RequestMapping("/like")
public class LikeController {
    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private LikeService likeService;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private DisccusPostService disccusPostService;

    @PostMapping
    @ResponseBody
    public String like(int entityType, int entityId, int entityUserId, int postId){
        int userId = hostHolder.getUser().getId();
        likeService.like(userId, entityType, entityId, entityUserId);
        int status = likeService.likeStatus(userId, entityType, entityId);
        long count = likeService.countEntityLikes(entityType, entityId);

        // 系统通知
        if (status == 1){
            Event event = new Event()
                    .setTopic(Topic.LIKE)
                    .setUserId(hostHolder.getUser().getId())
                    .setEntityType(entityType)
                    .setEntityId(entityId)
                    .setEntityUserId(entityUserId)
                    .setData("postId", postId);
            eventProducer.fireEvent(event);
        }

        if (entityType == Entity.DISCUSS_POST){
            // 帖子被点赞时更新 es
            Event event = new Event()
                    .setTopic(Topic.POST_PUBLISH)
                    .setEntityType(Entity.DISCUSS_POST)
                    .setEntityId(entityId);
            eventProducer.fireEvent(event);

            // 更新帖子分数
            disccusPostService.refreshScore(entityId);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("status", status);
        map.put("count", count);
        return CommunityUtils.getJsonString(200, "点赞成功", map);
    }
}
